package org.example.demo3.controller;

import lombok.RequiredArgsConstructor;

import org.example.demo3.enums.StatusCodeEnum;
import org.example.demo3.dto.LoginDTO;
import org.example.demo3.dto.LoginResponseDTO;
import org.example.demo3.dto.RegisterDTO;
import org.example.demo3.dto.RegisterResponseDTO;
import org.example.demo3.dto.ResetPasswordDTO;
import org.example.demo3.dto.ResponseDTO;
import org.example.demo3.dto.SendResetCodeDTO;
import org.example.demo3.dto.TokenDTO;
import org.example.demo3.dto.UpdateProfileDTO;
import org.example.demo3.service.UserService;
import org.example.demo3.untils.TokenUtil;
import org.example.demo3.vo.UserInfoVO;
import org.example.demo3.vo.UserVO;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    // 注入UserService依赖，使用final修饰，由构造函数注入
    private final UserService userService;
    // 注入TokenUtil依赖
    private final TokenUtil tokenUtil;

    /**
     * 用户注册
     * 支持请求体和查询参数两种方式
     */
    @PostMapping("/register")
    public ResponseDTO<RegisterResponseDTO> register(
            @RequestBody(required = false) RegisterDTO registerDTOFromBody,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Integer gender) {
        
        try {
            RegisterDTO registerDTO;
            
            // 如果请求体中有数据，优先使用请求体
            if (registerDTOFromBody != null) {
                registerDTO = registerDTOFromBody;
            } else {
                // 否则使用查询参数构建DTO
                registerDTO = new RegisterDTO();
                registerDTO.setUsername(username);
                registerDTO.setPassword(password);
                registerDTO.setNickname(nickname);
                registerDTO.setEmail(email);
                registerDTO.setGender(gender);
            }
            
            // 调用userService的register方法进行用户注册
            RegisterResponseDTO responseDTO = userService.register(registerDTO);
            // 返回成功的响应，包含用户基本信息
            return ResponseDTO.success(responseDTO);
        } catch (Exception e) {
            // 捕获异常，返回错误响应，包含错误码和错误信息
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 用户登录
     * 支持请求体和查询参数两种方式
     */
    @PostMapping("/login")
    public ResponseDTO<LoginResponseDTO> login(
            @RequestBody(required = false) LoginDTO loginDTOFromBody,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password) {
        
        try {
            LoginDTO loginDTO;
            
            // 如果请求体中有数据，优先使用请求体
            if (loginDTOFromBody != null) {
                loginDTO = loginDTOFromBody;
            } else {
                // 否则使用查询参数构建DTO
                loginDTO = new LoginDTO();
                loginDTO.setUsername(username);
                loginDTO.setPassword(password);
            }
            
            // 调用userService的login方法进行用户登录，传入登录信息
            LoginResponseDTO loginResponse = userService.login(loginDTO);
            // 返回成功的响应，包含token信息和用户基本信息
            return ResponseDTO.success(loginResponse);
        } catch (Exception e) {
            // 捕获异常，返回错误响应，包含错误码和错误信息
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 获取用户基本信息
     */
    @GetMapping("/info")
    public ResponseDTO<UserVO> getUserInfo(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取用户ID
            Long userId = tokenUtil.getUserIdFromHeader(token);
            UserVO userVO = userService.getUserVO(userId);
            return ResponseDTO.success(userVO);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 获取用户详细信息（当前登录用户）
     */
    @GetMapping("/detail")
    public ResponseDTO<UserInfoVO> getUserDetail(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取用户ID
            Long userId = tokenUtil.getUserIdFromHeader(token);
            UserInfoVO userInfoVO = userService.getUserInfoVO(userId);
            return ResponseDTO.success(userInfoVO);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 根据用户ID获取用户详细信息
     */
    @GetMapping("/detail/{userId}")
    public ResponseDTO<UserInfoVO> getUserDetailById(@PathVariable Long userId, 
                                                    @RequestHeader(value = "Authorization", required = false) String token ) {
        try {
            // 验证当前用户是否有权限查看此信息（可选，根据业务需求）
           // Long currentUserId = tokenUtil.getUserIdFromHeader(token);
            // 这里可以添加权限检查逻辑，例如只允许管理员或自己查看
            
            UserInfoVO userInfoVO = userService.getUserInfoVO(userId);
            return ResponseDTO.success(userInfoVO);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 刷新token
     * 支持请求体和查询参数两种方式
     */
    @PostMapping("/token/refresh")
    public ResponseDTO<TokenDTO> refreshToken(
            @RequestBody(required = false) Map<String, String> requestMap,
            @RequestParam(required = false) String refreshToken) {
        
        try {
            String tokenToRefresh = refreshToken;
            
            // 如果请求体中有数据，优先使用请求体
            if (requestMap != null && requestMap.containsKey("refreshToken")) {
                tokenToRefresh = requestMap.get("refreshToken");
            }
            
           if (tokenToRefresh == null || tokenToRefresh.isEmpty()) {
               return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, "刷新令牌不能为空");
            }
            
            TokenDTO tokenDTO = userService.refreshToken(tokenToRefresh);
            return ResponseDTO.success(tokenDTO);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 更新用户信息
     * 支持请求体和查询参数两种方式
     */
    @PostMapping("/profile")
    public ResponseDTO<UserInfoVO> updateProfile(
            @RequestHeader("Authorization") String token,
            @RequestBody(required = false) UpdateProfileDTO updateProfileDTOFromBody,
            @RequestParam String nickname,
            @RequestParam String email,
            @RequestParam Integer gender,
            @RequestParam String avatar) {
        
        try {
            UpdateProfileDTO updateProfileDTO;
            
            // 如果请求体中有数据，优先使用请求体
            if (updateProfileDTOFromBody != null) {
                updateProfileDTO = updateProfileDTOFromBody;
            } else {
                // 否则使用查询参数构建DTO
                updateProfileDTO = new UpdateProfileDTO();
                updateProfileDTO.setNickname(nickname);
                updateProfileDTO.setEmail(email);
                updateProfileDTO.setGender(gender);
                updateProfileDTO.setAvatar(avatar);
            }
            
            // 从token中获取用户ID
            Long userId = tokenUtil.getUserIdFromHeader(token);
            UserInfoVO userInfoVO = userService.updateProfile(userId, updateProfileDTO);
            return ResponseDTO.success(userInfoVO);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 发送重置密码验证码
     * 支持请求体和查询参数两种方式
     */
    @PostMapping("/password/reset-code")
    public ResponseDTO<Void> sendResetCode(
            @RequestBody(required = false) SendResetCodeDTO sendResetCodeDTOFromBody,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email) {
        
        try {
            SendResetCodeDTO sendResetCodeDTO;
            
            // 如果请求体中有数据，优先使用请求体
            if (sendResetCodeDTOFromBody != null) {
                sendResetCodeDTO = sendResetCodeDTOFromBody;
            } else {
                // 否则使用查询参数构建DTO
                sendResetCodeDTO = new SendResetCodeDTO();
                sendResetCodeDTO.setUsername(username);
                sendResetCodeDTO.setEmail(email);
            }
            
            userService.sendResetCode(sendResetCodeDTO);
            return ResponseDTO.success(null);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }

    /**
     * 重置密码
     * 支持请求体和查询参数两种方式
     */
    @PostMapping("/password/reset")
    public ResponseDTO<Void> resetPassword(
            @RequestBody(required = false) ResetPasswordDTO resetPasswordDTOFromBody,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String verificationCode,
            @RequestParam(required = false) String newPassword,
            @RequestParam(required = false) String confirmPassword) {
        
        try {
            ResetPasswordDTO resetPasswordDTO;
            
            // 如果请求体中有数据，优先使用请求体
            if (resetPasswordDTOFromBody != null) {
                resetPasswordDTO = resetPasswordDTOFromBody;
            } else {
                // 否则使用查询参数构建DTO
                resetPasswordDTO = new ResetPasswordDTO();
                resetPasswordDTO.setUsername(username);
                resetPasswordDTO.setVerificationCode(verificationCode);
                resetPasswordDTO.setNewPassword(newPassword);
                resetPasswordDTO.setConfirmPassword(confirmPassword);
            }
            
            userService.resetPassword(resetPasswordDTO);
            return ResponseDTO.success(null);
        } catch (Exception e) {
            return ResponseDTO.error(StatusCodeEnum.VALID_ERROR, e.getMessage());
        }
    }
}